package com.mxsoft.takeaway.util.eleme;

import eleme.openapi.sdk.config.Config;
import eleme.openapi.sdk.oauth.OAuthClient;
import eleme.openapi.sdk.oauth.response.Token;
import eleme.openapi.sdk.utils.PropertiesUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ElemeUtil {
    private static Config config = null;

    private static OAuthClient client = null;

    private static Map<String, String> tokenMap = new HashMap<String, String>();


    static {
        URL resource = Thread.currentThread().getContextClassLoader().getResource("eleme.properties");
        File file = new File(resource.getPath());
        if (!file.exists()) {
            throw new RuntimeException("eleme.properties配置文件不存在");
        }
        try {
            Properties properties = new Properties();
            properties.load(new FileReader(file));

            if (StringUtils.isEmpty(properties.getProperty("key"))
                    || StringUtils.isEmpty(properties.getProperty("secret"))
                    ) {
                throw new RuntimeException("eleme配置文件配置错误");
            }

            if (!StringUtils.isEmpty(properties.getProperty("isSandbox"))) {
                config = new Config(Boolean.valueOf(properties.getProperty("isSandbox")), properties.getProperty("key"), properties.getProperty("secret"));
            } else {
                config = new Config(true, properties.getProperty("key"), properties.getProperty("secret"));
            }
            client = new OAuthClient(config);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Config getConfig() {
        return config;
    }

    public static Token getToken() {
        Token token = client.getTokenInClientCredentials();
        if (token.isSuccess()) {
            setTokenInfo(token);
            System.out.println(token);
        } else {
            throw new RuntimeException("获取token失败");
        }
        return token;
    }

    private static void setTokenInfo(Token token) {
        if (null != token && token.isSuccess()) {
            tokenMap.put("access_token", token.getAccessToken());
            tokenMap.put("token_type", token.getTokenType());
            tokenMap.put("expires_in", String.valueOf(token.getExpires()));
            tokenMap.put("refresh_token", token.getRefreshToken());
            PropertiesUtils.setProps(tokenMap);
        }
    }
}
